package com.bi.bitest.bao.utils;

import android.os.Build;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.GZIPInputStream;

/**
 * Created with IntelliJ IDEA.
 * User: vhly[FR]
 * Date: 15/10/12
 * Email: vhly@163.com
 *
 * HTTP请求工具类
 */

public final class HttpTools {

    private HttpTools() {

    }
     private static final int CONNECT_TIMEOUT=5000;
     private static final int READE_TIMEOUT=10000;
    private static final String USER_AGENT="ting_4.1.7("+Build.MODEL+","+Build.VERSION.SDK_INT+")";

    public static byte[] doGet(String url) {
        byte[] ret = null;

        if (url != null) {
            HttpURLConnection conn = null;
            try {
                URL u = new URL(url);
                conn = (HttpURLConnection) u.openConnection();
                conn.setConnectTimeout(CONNECT_TIMEOUT);
                conn.setReadTimeout(READE_TIMEOUT);
                conn.setRequestMethod("GET");
                //完善HTTP请求的内容
                //设置通用的H天天碰头信息
                //可接受的类型
               // conn.setRequestProperty("Accept","application/*,text/*,image/*,*/*");
                //设置接受的内容压缩算法
                conn.setRequestProperty("Accept-Encoding","gzip");
                //设置Useragent
                conn.setRequestProperty("User-Agent",USER_AGENT);

                conn.connect();
                int code = conn.getResponseCode();
                if (code == 200) {
                    // TODO 给 data 赋值
                    InputStream fin = null;
                    try {
                        fin = conn.getInputStream();
                        //TODO 进行网络输入流的gzip压缩
                        String encoding=conn.getHeaderField("Content-Encoding");
                        if("gzip".equals(encoding)){
                            fin=new GZIPInputStream(fin);
                        }

                        ret = StreamUtil.readStream(fin);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        StreamUtil.close(fin);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                StreamUtil.close(conn);
            }

        }

        return ret;
    }


}
